package com.crazecoder.flutter.alibc;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.ali.auth.third.core.model.Session;
import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeInitCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcDetailPage;
import com.alibaba.baichuan.android.trade.page.AlibcShopPage;
import com.alibaba.baichuan.trade.biz.applink.adapter.AlibcFailModeType;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams;
import com.alibaba.baichuan.trade.biz.login.AlibcLogin;
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback;

import java.util.HashMap;
import java.util.Map;

import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

import com.crazecoder.flutter.alibc.bean.ResultInfo;
import com.crazecoder.flutter.alibc.utils.JsonUtil;
import com.crazecoder.flutter.alibc.utils.MapUtil;


/**
 * FlutterAlibcPlugin
 */
public class FlutterAlibcPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private static final String TAG = "flutter_alibc";
    private MethodChannel channel;
    private Context context;
    private Activity activity;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_alibc");
        context = flutterPluginBinding.getApplicationContext();
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull final Result result) {
        if (call.method.equals("initSdk")) {
            final ResultInfo bean = new ResultInfo();
            AlibcTradeSDK.asyncInit((Application) context, new AlibcTradeInitCallback() {
                @Override
                public void onSuccess() {
                    bean.setSuccess(true);
                    bean.setMessage("初始化成功");
                    result.success(JsonUtil.toJson(MapUtil.deepToMap(bean)));
                }

                @Override
                public void onFailure(int code, String msg) {
                    bean.setSuccess(false);
                    bean.setMessage("初始化失败:" + msg);
                    result.success(JsonUtil.toJson(MapUtil.deepToMap(bean)));
                }
            });
        } else if (call.method.equals("getLoginSession")) {
            Session session = AlibcLogin.getInstance().getSession();
            result.success(JsonUtil.toJson(MapUtil.deepToMap(session)));
        } else if (call.method.equals("login")) {
            AlibcLogin alibcLogin = AlibcLogin.getInstance();
            alibcLogin.showLogin(new AlibcLoginCallback() {
                @Override
                public void onSuccess(int loginResult, String openId, String userNick) {
                    // 参数说明：
                    // loginResult(0--登录初始化成功；1--登录初始化完成；2--登录成功)
                    // openId：用户id
                    // userNick: 用户昵称
                    Session session = AlibcLogin.getInstance().getSession();
                    result.success(JsonUtil.toJson(MapUtil.deepToMap(session)));
                }

                @Override
                public void onFailure(int code, String msg) {
                    // code：错误码  msg： 错误信息
                    result.success(msg);
                }
            });

        } else if (call.method.equals("loginout")) {
            AlibcLogin alibcLogin = AlibcLogin.getInstance();
            alibcLogin.logout(new AlibcLoginCallback() {
                @Override
                public void onSuccess(int loginResult, String openId, String userNick) {
                    // 参数说明：
                    // loginResult(3--登出成功)
                    // openId：用户id
                    // userNick: 用户昵称
                    result.success(true);
                }

                @Override
                public void onFailure(int code, String msg) {
                    // code：错误码  msg： 错误信息
                    Log.e(TAG, "取消授权错误：code=" + code + "  msg=" + msg);
                    result.success(false);
                }
            });

        } else if (call.method.equals("openByBizCode")) {
            String pid = null;
            String adzoneid = null;
            String taokeAppkey = null;
            String sellerId = null;
            String itemId = null;
            String shopId = null;
            if (call.hasArgument("pid")) {
                pid = call.argument("pid");
            }
            if (call.hasArgument("adzoneid")) {
                adzoneid = call.argument("adzoneid");
            }
            if (call.hasArgument("taokeAppkey")) {
                taokeAppkey = call.argument("taokeAppkey");
            }
            if (call.hasArgument("sellerId")) {
                sellerId = call.argument("sellerId");
            }
            if (call.hasArgument("itemId")) {
                itemId = call.argument("itemId");
            }
            if (call.hasArgument("shopId")) {
                shopId = call.argument("shopId");
            }
            openByBizCode(pid, adzoneid, taokeAppkey, sellerId, itemId, shopId);
            result.success(null);
        } else if (call.method.equals("openByUrl")) {
            String pid = null;
            String adzoneid = null;
            String taokeAppkey = null;
            String sellerId = null;
            String url = null;
            if (call.hasArgument("pid")) {
                pid = call.argument("pid");
            }
            if (call.hasArgument("adzoneid")) {
                adzoneid = call.argument("adzoneid");
            }
            if (call.hasArgument("taokeAppkey")) {
                taokeAppkey = call.argument("taokeAppkey");
            }
            if (call.hasArgument("sellerId")) {
                sellerId = call.argument("sellerId");
            }
            if (call.hasArgument("url")) {
                url = call.argument("url");
            }
            openByUrl(pid, adzoneid, taokeAppkey, sellerId, url);
            result.success(null);
        } else {
            result.notImplemented();
        }
    }

    private void openByUrl(String pid,
                           String adzoneid,
                           String taokeAppkey,
                           String sellerId,
                           String url) {
        //展示参数配置
        AlibcShowParams showParams = new AlibcShowParams();
        showParams.setOpenType(OpenType.Auto);
        showParams.setClientType("taobao");
        showParams.setBackUrl("alisdk://");
        showParams.setNativeOpenFailedMode(AlibcFailModeType.AlibcNativeFailModeJumpBROWER);
        /** showParam各参数介绍
         1、OpenType（页面打开方式）： 枚举值（Auto和Native），Native表示唤端，Auto表示不做设置
         2、clientType表示唤端类型：taobao---唤起淘宝客户端；tmall---唤起天猫客户端
         3、BACK_URL（小把手）：唤端返回的scheme
         (如果不传默认将不展示小把手；如果想展示小把手，可以自己传入自定义的scheme，
         或者传入百川提供的默认scheme："alisdk://")
         4、AlibcFailModeType（唤端失败模式）： 枚举值如下
         AlibcNativeFailModeNONE：不做处理；
         AlibcNativeFailModeJumpBROWER：跳转浏览器；
         AlibcNativeFailModeJumpDOWNLOAD：跳转下载页；
         AlibcNativeFailModeJumpH5：应用内webview打开）
         （注：AlibcNativeFailModeJumpBROWER不推荐使用）*/

        /** taokeParams（淘客）参数配置：配置aid或pid的方式分佣
         //    参数说明：
         //    pid
         //            unionId
         //    subPid
         //            adzoneId
         //    extraParams
         //（注：1、如果走adzoneId的方式分佣打点，需要在extraParams中显式传入taokeAppkey，否则打点失败；
         //    2、如果是打开店铺页面(shop)，需要在extraParams中显式传入sellerId，否则同步打点转链失败）*/
        AlibcTaokeParams taokeParams = new AlibcTaokeParams("", "", "");
        if (!TextUtils.isEmpty(pid))
            taokeParams.setPid(pid);
        if (!TextUtils.isEmpty(adzoneid))
            taokeParams.setAdzoneid(adzoneid);
        //adzoneid是需要taokeAppkey参数才可以转链成功&店铺页面需要卖家id（sellerId），具体设置方式如下：
        if (!TextUtils.isEmpty(taokeAppkey))
            taokeParams.extraParams.put("taokeAppkey", taokeAppkey);
        if (!TextUtils.isEmpty(sellerId))
            taokeParams.extraParams.put("sellerId", sellerId);

        //自定义参数
        Map<String, String> trackParams = new HashMap<>();
        // 以显示传入url的方式打开页面（第二个参数是套件名称）
        AlibcTrade.openByUrl(activity, "", url, null,
                new WebViewClient(), new WebChromeClient(), showParams,
                taokeParams, trackParams, new AlibcTradeCallback() {
                    @Override
                    public void onTradeSuccess(AlibcTradeResult tradeResult) {
//                AlibcLogger.i(TAG, "request success");
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        Log.e(TAG, "打开界面出错：code=" + code + "  msg=" + msg);

                    }
                });
    }

    private void openByBizCode(String pid,
                               String adzoneid,
                               String taokeAppkey,
                               String sellerId,
                               String itemId,
                               String shopId) {
        // 以code的方式打开电商页面（eg：详情--detail，店铺--shop）

// 页面实例
        AlibcBasePage page;
        if (TextUtils.isEmpty(itemId)) {
            page = new AlibcDetailPage(itemId);
        } else {
            page = new AlibcShopPage(shopId);
        }
//展示参数配置
        AlibcShowParams showParams = new AlibcShowParams();
        showParams.setOpenType(OpenType.Native);
        showParams.setClientType("taobao");
        showParams.setBackUrl("alisdk://");
        showParams.setNativeOpenFailedMode(AlibcFailModeType.AlibcNativeFailModeJumpH5);
        /** showParam各参数介绍
         1、OpenType（页面打开方式）： 枚举值（Auto和Native），Native表示唤端，Auto表示不做设置
         2、clientType表示唤端类型：taobao---唤起淘宝客户端；tmall---唤起天猫客户端
         3、BACK_URL（小把手）：唤端返回的scheme
         (如果不传默认将不展示小把手；如果想展示小把手，可以自己传入自定义的scheme，
         或者传入百川提供的默认scheme："alisdk://")
         4、AlibcFailModeType（唤端失败模式）： 枚举值如下
         AlibcNativeFailModeNONE：不做处理；
         AlibcNativeFailModeJumpBROWER：跳转浏览器；
         AlibcNativeFailModeJumpDOWNLOAD：跳转下载页；
         AlibcNativeFailModeJumpH5：应用内webview打开）
         （注：AlibcNativeFailModeJumpBROWER不推荐使用）*/

        /** taokeParams（淘客）参数配置：配置aid或pid的方式分佣
         //    参数说明：
         //    pid
         //            unionId
         //    subPid
         //            adzoneId
         //    extraParams
         //（注：1、如果走adzoneId的方式分佣打点，需要在extraParams中显式传入taokeAppkey，否则打点失败；
         //    2、如果是打开店铺页面(shop)，需要在extraParams中显式传入sellerId，否则同步打点转链失败）*/
        AlibcTaokeParams taokeParams = new AlibcTaokeParams("", "", "");
        taokeParams.setPid(pid);
        if (!TextUtils.isEmpty(adzoneid))
            taokeParams.setAdzoneid(adzoneid);
        //adzoneid是需要taokeAppkey参数才可以转链成功&店铺页面需要卖家id（sellerId），具体设置方式如下：
        if (!TextUtils.isEmpty(taokeAppkey))
            taokeParams.extraParams.put("taokeAppkey", taokeAppkey);
        if (!TextUtils.isEmpty(sellerId))
            taokeParams.extraParams.put("sellerId", sellerId);

        //自定义参数
        Map<String, String> trackParams = new HashMap<>();


        AlibcTrade.openByBizCode(activity, page, null, new WebViewClient(),
                new WebChromeClient(), "detail", showParams, taokeParams,
                trackParams, new AlibcTradeCallback() {
                    @Override
                    public void onTradeSuccess(AlibcTradeResult tradeResult) {
                        // 交易成功回调（其他情形不回调）
//                AlibcLogger.i(TAG, "open detail page success");
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        // 失败回调信息
//                AlibcLogger.e(TAG, "code=" + code + ", msg=" + msg);
                        if (code == -1) {
                            Toast.makeText(context, "唤端失败，失败模式为none",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }


    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

    }

    @Override
    public void onDetachedFromActivity() {

    }
}
